
import ctypes
import sys
import os
import time

from serial_operation import SerialOperation

cur_status = 0
so = SerialOperation()

def status_change(new_status):
    global cur_status
    print("status change to {} from {}".format(new_status, cur_status))
    cur_status = new_status

def save_image_to_file(filename):
    global so
    image_size = 0
    st = 0
    while True:
        if st == 0:
            buf = so.read(1)
            if buf[0] == 0x9A:
                st = 1
        elif st == 1:
            buf = so.read(1)
            if buf[0] == 0xd2:
                st = 2
        elif st == 2:
            buf = so.read(1)
            if buf[0] == 0x0:
                st = 3
        elif st == 3:
            buf = so.read(5)
            if buf[0] == 0xE1:
                print("image not exist")
                break
            else:
                image_size = int.from_bytes(buf[1:4], byteorder='little')
                print("find image size {}, {}".format(buf[1:4].hex(), image_size))
                break

    print("image size {}".format(image_size))
    remain = image_size
    f = open(filename, 'wb')
    readblock = 10240
    while remain > 0:
        if remain < 10240:
            readblock = remain
        print("readblock {}", readblock)
        buf = so.read(readblock)
        n = f.write(buf)
        print("write {} bytes".format(n))
        remain -= len(buf)
        print("remain: {}", format(remain))
    f.close()

def start_recv_image_data(count, angle):
    global so
    buf = bytearray([0x7A, 0xD2, 0x00])
    buf_count = count.to_bytes(4, byteorder='little')
    buf_angle = angle.to_bytes(1, byteorder='little')
    buf+=buf_count
    buf+=buf_angle
    time.sleep(0.5)
    print("send data:{} {} {} {} {} {} {} {}".format(buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6], buf[7]))
    ret = so.sendData(buf)
    print("send result {}", format(ret))
    filename = "./img-%d-%d.jpg" % (count, angle)
    save_image_to_file(filename)

def recv_image_data():
    global so
    so.refresh()
    isOpen = so.open(0)
    print("open serial {}", format(isOpen))
    cur_cmd = 0
    while True:
        if cur_status == 0:
            buf = so.read(1)
            if buf is not None:
                if buf[0] == 0x7A:
                    status_change(1)
                    continue
        elif cur_status == 1:
            buf = so.read(1)
            if buf is not None:
                if buf[0] == 0xF2:
                    status_change(2)
                    continue
        elif cur_status == 2:
            buf = so.read(1)
            if buf is not None:
                status_change(3)
                continue
        elif cur_status == 3:
            buf = so.read(5)
            if buf is not None:
                buf_count = buf[0:3]
                count = int.from_bytes(buf_count, byteorder='little')
                buf_angle = buf[4]
                print("count:{}, angle:{}".format(count, buf_angle))
                start_recv_image_data(count, buf_angle)
                status_change(0)
                continue


def is_admin():
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False

if is_admin():
    # 你的脚本内容
    print("Running as admin")
else:
    # 重新以管理员权限运行脚本
    ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)

if __name__ == '__main__':
    print('PyCharm')
    recv_image_data()
